<?php

namespace backend\models;

use backend\components\GoodsCategoryQuery;
use creocoder\nestedsets\NestedSetsBehavior;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\helpers\Json;

/**
 * This is the model class for table "goods_category".
 *
 * @property string $id
 * @property integer $tree
 * @property string $lft
 * @property string $rgt
 * @property string $depth
 * @property string $name
 * @property string $parent_id
 * @property string $intro
 */
class GoodsCategory extends ActiveRecord
{



    /**
     *  @return array
     */
    public function behaviors() {
        return [
            'tree' => [
                'class' => NestedSetsBehavior::className(),
                'treeAttribute' => 'tree',
                // 'leftAttribute' => 'lft',
                // 'rightAttribute' => 'rgt',
                // 'depthAttribute' => 'depth',
            ],

        ];
    }
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'goods_category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['tree', 'lft', 'rgt', 'depth', 'parent_id'], 'integer'],
            [['parent_id','name'], 'required'],
            [['intro'], 'string'],
            [['name'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'tree' => '树的编号',
            'lft' => '左边界',
            'rgt' => '右边界',
            'depth' => '级别',
            'name' => '名称',
            'parent_id' => '上级分类',
            'intro' => '简介',
        ];
    }



    /**
     * @return array
     */
    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }

    public static function find()
    {
        return new GoodsCategoryQuery(get_called_class());
    }

    /**
     * 保存节点数据
     * @return mixed
     */
    public function addNode(){
        //通过捕获异常,提示错误
        try{
            //添加节点
            //如果parent_id=1 创建根节点
            if($this->parent_id ==0){
                return $this->makeRoot();
            }else{
                $parentNode = GoodsCategory::findOne(['id'=>$this->parent_id]);

                return $this->prependTo($parentNode);
            }
        }catch (Exception $exception){
            //var_dump($exception->getMessage());
            $this->addError('parent_id',$exception->getMessage());
        }

        return false;
    }

    /**
     * 返回json格式的所有的分类的数据
     * @return array|string|ActiveRecord[]
     */
    public static function getGoodsCategorys(){
        //获取所有的已经存在的分类
        $models = GoodsCategory::find()->asArray()->all();
        $models[]=['id'=>0,'parent_id'=>0,'name'=>'顶级分类'];
        //并且转换为数组
        $models = Json::encode($models);

        return $models;
    }


}
